// utils/bluetooth.js
class BluetoothManager {
  constructor() {
    this.deviceId = null
    this.serviceId = null
    this.characteristicId = null
    this.isConnected = false
  }

  /**
   * 初始化蓝牙适配器
   */
  initBluetooth() {
    return new Promise((resolve, reject) => {
      uni.openBluetoothAdapter({
        success: (res) => {
          console.log('蓝牙初始化成功', res)
          resolve(res)
        },
        fail: (err) => {
          console.error('蓝牙初始化失败', err)
          uni.showToast({
            title: '蓝牙初始化失败',
            icon: 'none'
          })
          reject(err)
        }
      })
    })
  }

  /**
   * 搜索蓝牙设备
   */
  searchDevices() {
    return new Promise((resolve, reject) => {
      uni.startBluetoothDevicesDiscovery({
        allowDuplicatesKey: false,
        success: (res) => {
          console.log('开始搜索蓝牙设备', res)

          // 监听寻找到新设备的事件
          uni.onBluetoothDeviceFound((res) => {
            const devices = res.devices
            resolve(devices)
          })
        },
        fail: (err) => {
          console.error('搜索蓝牙设备失败', err)
          reject(err)
        }
      })
    })
  }

  /**
   * 连接蓝牙设备
   * @param {string} deviceId - 设备ID
   */
  connectDevice(deviceId) {
    return new Promise((resolve, reject) => {
      uni.createBLEConnection({
        deviceId: deviceId,
        success: (res) => {
          console.log('连接蓝牙设备成功', res)
          this.deviceId = deviceId
          this.isConnected = true
          resolve(res)
        },
        fail: (err) => {
          console.error('连接蓝牙设备失败', err)
          uni.showToast({
            title: '连接设备失败',
            icon: 'none'
          })
          reject(err)
        }
      })
    })
  }

  /**
   * 获取设备服务
   */
  getDeviceServices() {
    return new Promise((resolve, reject) => {
      uni.getBLEDeviceServices({
        deviceId: this.deviceId,
        success: (res) => {
          console.log('获取设备服务成功', res)
          // 这里需要根据实际设备的服务ID来选择
          this.serviceId = res.services[0].uuid
          resolve(res.services)
        },
        fail: (err) => {
          console.error('获取设备服务失败', err)
          reject(err)
        }
      })
    })
  }

  /**
   * 获取特征值
   */
  getDeviceCharacteristics() {
    return new Promise((resolve, reject) => {
      uni.getBLEDeviceCharacteristics({
        deviceId: this.deviceId,
        serviceId: this.serviceId,
        success: (res) => {
          console.log('获取特征值成功', res)
          // 根据实际需要选择读写特征值
          this.characteristicId = res.characteristics[0].uuid
          resolve(res.characteristics)
        },
        fail: (err) => {
          console.error('获取特征值失败', err)
          reject(err)
        }
      })
    })
  }

  /**
   * 发送数据到设备
   * @param {string} data - 要发送的数据
   */
  sendToDevice(data) {
    return new Promise((resolve, reject) => {
      // 将数据转换为 ArrayBuffer
      const buffer = new ArrayBuffer(data.length)
      const dataView = new DataView(buffer)
      for (let i = 0; i < data.length; i++) {
        dataView.setUint8(i, data.charCodeAt(i))
      }

      uni.writeBLECharacteristicValue({
        deviceId: this.deviceId,
        serviceId: this.serviceId,
        characteristicId: this.characteristicId,
        value: buffer,
        success: (res) => {
          console.log('发送数据成功', res)
          resolve(res)
        },
        fail: (err) => {
          console.error('发送数据失败', err)
          reject(err)
        }
      })
    })
  }

  /**
   * 断开蓝牙连接
   */
  disconnect() {
    if (this.deviceId) {
      uni.closeBLEConnection({
        deviceId: this.deviceId,
        success: () => {
          console.log('断开蓝牙连接成功')
          this.deviceId = null
          this.isConnected = false
        },
        fail: (err) => {
          console.error('断开蓝牙连接失败', err)
        }
      })
    }
  }
}

// 创建蓝牙管理实例
const bluetoothManager = new BluetoothManager()

export default bluetoothManager
